# -*- coding: utf-8 -*
from flask import Flask, jsonify
from flask_cors import CORS
from typing import List
from utils.gen import generate_data_key

# 左闭右开
interval = {
    "cpu": (0, 11),
    "disk": (11, 31),
    "memory": (31, 34),
    "network": (34, 39)
}


class Gateway:
    """网关类：用于展示各性能数据"""
    def __init__(self, data_list: List[float], host="0.0.0.0", port=2233, debug=False):
        self.app = Flask(__name__)
        self.data_list = data_list
        self.host = host
        self.port = port
        self.debug = debug
        CORS(self.app, origins="*")
        self.app.add_url_rule('/cpu', view_func=self.cpu)
        self.app.add_url_rule('/disk', view_func=self.disk)
        self.app.add_url_rule('/memory', view_func=self.memory)
        self.app.add_url_rule('/network', view_func=self.network)

    def cpu(self):
        data = generate_data_key("cpu")
        rsp = {
            "code": 200,
            "status": "ok",
            "data": data,
        }

        start = interval["cpu"][0]
        end = interval["cpu"][1]
        for i in range(start, end):
            metric = self.data_list[i]
            for index, key in enumerate(data):
                if i == index:
                    data[key] = metric

        return jsonify(rsp)

    def disk(self):
        data = generate_data_key("disk")
        rsp = {
            "code": 200,
            "status": "ok",
            "data": data,
        }

        start = interval["disk"][0]
        end = interval["disk"][1]
        for i in range(start, end):
            metric = self.data_list[i]
            prelen = interval["cpu"][1] - interval["cpu"][0]
            for index, key in enumerate(data):
                if i == index + prelen:
                    data[key] = metric

        return jsonify(rsp)

    def memory(self):
        data = generate_data_key("memory")
        rsp = {
            "code": 200,
            "status": "ok",
            "data": data,
        }

        start = interval["memory"][0]
        end = interval["memory"][1]
        for i in range(start, end):
            metric = self.data_list[i]
            prelen = interval["disk"][1] - interval["cpu"][0]
            for index, key in enumerate(data):
                if i == index + prelen:
                    data[key] = metric

        return jsonify(rsp)

    def network(self):
        data = generate_data_key("network")
        rsp = {
            "code": 200,
            "status": "ok",
            "data": data
        }

        start = interval["network"][0]
        end = interval["network"][1]
        for i in range(start, end):
            metric = self.data_list[i]
            prelen = interval["memory"][1] - interval["cpu"][0]
            for index, key in enumerate(data):
                if i == index + prelen:
                    data[key] = metric

        return jsonify(rsp)

    def run(self):
        self.app.run(host=self.host, port=self.port, debug=self.debug)

